/**
 * 
 */
package kr.co.insoft.core.service.orchestration.impl;

import java.util.ArrayList;
import java.util.List;

import kr.co.insoft.core.model.orchestration.OrchestrationTreeEntityModel;
import kr.co.insoft.core.model.orchestration.OrchestrationTreeMetadataEntityModel;

import org.apache.commons.collections.Predicate;

/**
 * @author IN-SOFT Inc. GoodwillDD(sylee@in-soft.co.kr)
 *
 */
public class OrchestrationTreeCompute {

	final List<OrchestrationTreeMetadataEntityModel> treeData;

	public OrchestrationTreeCompute(
			List<OrchestrationTreeMetadataEntityModel> treeData) {
		this.treeData = treeData;
	}

	public OrchestrationTreeEntityModel getTree() {
		OrchestrationTreeEntityModel rootEntity = getRoot();
		rootEntity.setChildren(getChild(treeData, getRootMetadata()));
		return rootEntity;
	}

	public List<OrchestrationTreeEntityModel> getTreeNonRoot() {
		return getChild(treeData, getRootMetadata());
	}

	private OrchestrationTreeMetadataEntityModel getRootMetadata() {
		OrchestrationTreeMetadataEntityModel entity = new OrchestrationTreeMetadataEntityModel();
		entity.setName("CLOUD");
		entity.setChild_uid("0");
		entity.setExpand(true);
		entity.setTypes("ROOT");
		return entity;
	}

	private OrchestrationTreeEntityModel getRoot() {
		OrchestrationTreeEntityModel tree = new OrchestrationTreeEntityModel();
		tree.setMetadata(getRootMetadata());
		tree.setTitle(getRootMetadata().getName());
		tree.setExpand(true);
		return tree;
	}

	@SuppressWarnings("unchecked")
	private List<OrchestrationTreeEntityModel> getChild(
			List<OrchestrationTreeMetadataEntityModel> tree,
			final OrchestrationTreeMetadataEntityModel rootMetadata) {
		ArrayList<OrchestrationTreeMetadataEntityModel> findGroups = new ArrayList<OrchestrationTreeMetadataEntityModel>();
		findGroups = new ArrayList<OrchestrationTreeMetadataEntityModel>(
				org.apache.commons.collections.CollectionUtils.select(tree,
						new Predicate() {
							public boolean evaluate(Object obj) {
								return ((OrchestrationTreeMetadataEntityModel) obj)
										.getParent_uid().equals(
												rootMetadata.getChild_uid());
							}
						}));
		List<OrchestrationTreeEntityModel> result = new ArrayList<OrchestrationTreeEntityModel>();
		OrchestrationTreeEntityModel te = null;
		for (OrchestrationTreeMetadataEntityModel item : findGroups) {
			te = new OrchestrationTreeEntityModel();
			te.setMetadata(item);
			te.setTitle(item.getName() + "(" + item.getChild_count() + ")");
			te.setChildren(getChild(tree, item));
			te.setExpand(item.isExpand());
			result.add(te);
		}
		return result;
	}
}
